#!/bin/sh

DATA_DIR="/srv/tusd-data/data"
MC="/opt/bin/mc --config-dir /etc/minio/mc"

log() {
  echo "[tus_id:$TUS_ID] $@"
}

connect() {
  if [ -f "/etc/minio/mc/config.json" ]; then
    return 0
  fi
  $MC config host add minio http://${MINIO_ENDPOINT}:${MINIO_PORT} $(cat /config/accesskey) $(cat /config/secretkey)
  return 0
}

# connect to minio service
connect

# fetch information
log "Upload $TUS_ID ($TUS_SIZE bytes) finished"
info=`cat /dev/stdin`

tus_id=$TUS_ID
filename=`echo $info | jq -r .Upload.MetaData.filename`
dirpath=`echo $info | jq -r .Upload.MetaData.dirpath`
if ! echo $dirpath | grep -qE '/$' ; then
  dirpath="${dirpath}/"
fi

log metadata "$(echo $info | jq -c .Upload.MetaData)"
log "tus_id $tus_id, filename $filename, dirpath $dirpath, bucket $BUCKET_NAME"

result=$($MC mv --disable-multipart "${DATA_DIR}/${tus_id}" "minio/${BUCKET_NAME}/${dirpath}${filename}")
log mv result: $result
rm "${DATA_DIR}/${tus_id}.info"
